<template>
  <a-modal
    v-model:open="visible"
    title="角色管理"
    :width="500"
    :loading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="role-management">
      <div class="role-list">
        <div 
          v-for="role in roles" 
          :key="role.id"
          class="role-item"
        >
          <div class="role-user-info">
            <a-avatar 
              :size="36"
              :src="role.avatarUrl"
              :style="role.avatarUrl ? {} : { backgroundColor: getRoleColor(role.id), color: 'white' }"
            >
              {{ (role.roleName || '角色')[0]?.toUpperCase() || 'R' }}
            </a-avatar>
            <div class="role-user-details">
              <div class="role-user-name">{{ role.roleName }}</div>
              <div class="role-user-status">{{ role.prompt || '暂无描述' }}</div>
            </div>
          </div>
          <div class="role-actions">
            <a-switch 
              v-model:checked="role.isEnabled"
              @change="handleToggleRoleStatus(role.id)"
            />
            <span class="mute-label">启用</span>
          </div>
        </div>
      </div>
      
      <div v-if="roles.length === 0 && !loading" class="empty-state">
        <div class="empty-icon">🤖</div>
        <div class="empty-text">暂无角色</div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import { Codewin } from '@/api/generated/Codewin'
import type { ChatRoomRoleVO } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores'

interface ExtendedRole extends ChatRoomRoleVO {
  isEnabled: boolean
}

interface Props {
  open: boolean
  roomId?: string
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'save'): void
}

const props = withDefaults(defineProps<Props>(), {
  roomId: ''
})

const emit = defineEmits<Emits>()

// 响应式状态
const visible = ref(false)
const loading = ref(false)
const roles = ref<ExtendedRole[]>([])

// 获取认证store
const authStore = useAuthStore()

// 创建API实例，配置认证
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  securityWorker: (securityData) => {
    const token = authStore.token
    return token ? { headers: { Authorization: `Bearer ${token}` } } : {}
  }
})

// 监听 props.open 变化
watch(() => props.open, async (newVal) => {
  visible.value = newVal
  if (newVal && props.roomId) {
    await fetchRoles()
  }
})

// 监听 visible 变化
watch(visible, (newVal) => {
  emit('update:open', newVal)
})

// 获取角色列表
const fetchRoles = async () => {
  if (!props.roomId) {
    message.error('聊天室ID不能为空')
    return
  }

  loading.value = true
  try {
    const response = await api.getChatRoomRoles(props.roomId)
    if (response.data?.code === 0 && response.data?.data) {
      roles.value = response.data.data.map((role: ChatRoomRoleVO) => ({
        ...role,
        isEnabled: true // 默认所有角色都启用
      }))
    } else {
      message.error(response.data?.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    message.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色颜色
const getRoleColor = (roleId?: string) => {
  const colors = [
    '#6366f1', '#8b5cf6', '#ec4899', '#ef4444',
    '#f59e0b', '#10b981', '#06b6d4', '#3b82f6'
  ]
  if (!roleId) return colors[0]
  const index = roleId.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return colors[index % colors.length]
}

// 处理角色状态切换
const handleToggleRoleStatus = (roleId?: string) => {
  const role = roles.value.find(r => r.id === roleId)
  if (role) {
    message.success(role.isEnabled ? '角色已启用' : '角色已禁用')
  }
}

// 获取启用的角色ID列表
const enabledRoleIds = computed(() => {
  return roles.value
    .filter(role => role.isEnabled && role.id)
    .map(role => role.id)
})

// 处理确认
const handleOk = async () => {
  if (!props.roomId) {
    message.error('聊天室ID不能为空')
    return
  }

  loading.value = true
  try {
    const response = await api.bindChatRoomRoles({
      roomId: props.roomId,
      roleIds: enabledRoleIds.value.filter(id => id !== undefined) as string[],
    })
    
    if (response.data?.code === 0) {
      message.success('角色设置保存成功')
      emit('save')
      visible.value = false
    } else {
      message.error(response.data?.message || '保存失败')
    }
  } catch (error) {
    console.error('保存角色设置失败:', error)
    message.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  visible.value = false
}
</script>

<style scoped>
.role-management {
  padding: 8px 0;
}

.role-list {
  max-height: 400px;
  overflow-y: auto;
}

.role-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.role-item:last-child {
  border-bottom: none;
}

.role-user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.role-user-details {
  flex: 1;
}

.role-user-name {
  font-weight: 500;
  color: #262626;
  font-size: 14px;
  margin-bottom: 2px;
}

.role-user-status {
  font-size: 12px;
  color: #8c8c8c;
}

.role-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.mute-label {
  font-size: 12px;
  color: #595959;
  white-space: nowrap;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #8c8c8c;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-text {
  font-size: 14px;
}

/* 滚动条样式 */
.role-list::-webkit-scrollbar {
  width: 4px;
}

.role-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.role-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.role-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

:deep(.ant-switch) {
  min-width: 44px;
}

:deep(.ant-switch-checked) {
  background-color: #ff4d4f;
}

:deep(.ant-switch-checked:hover:not(.ant-switch-disabled)) {
  background-color: #ff7875;
}
</style>